package chat.keepWind.handle;

import java.io.RandomAccessFile;

import javax.swing.ProgressMonitor;

import chat.keepWind.bean.DataPackage;
import chat.keepWind.ui.ChatUI;
import chat.keepWind.util.ChatUtil;
import chat.keepWind.util.GlobalConst;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

public class RcvFileInboundHandler extends SimpleChannelInboundHandler<DataPackage> {
	private ProgressMonitor progress;
	private int cnt=1; //次数
	
	
	
	@Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace(); 
        ctx.close();
    }
	
	@Override
    public void channelRead0(ChannelHandlerContext ctx, DataPackage data) throws Exception {
		//接收到文件
		String fromIp = data.getFromIp();
    	String toIp = data.getToIp();
		
		if(data.getFileLen()==0){
			ctx.close();
			System.out.println("文件不存在或出错！");
			return;
		}
		if(cnt!=data.getFileNo()){//序号不一致，重发
			data.setFromIp(toIp);
			data.setToIp(fromIp);
			data.setFlag((byte)2);
			data.setMsgContent("".getBytes(CharsetUtil.UTF_8));
			data.setPoint((cnt-1)*GlobalConst.BYTE_NUM);
			ctx.writeAndFlush(data).sync();
			return;
		}
		
		
		String nickName = ChatUtil.getNickName(data.getFromIp());
		ChatUI chat = ChatUtil.openChat(data.getFromIp(),nickName);
		if(progress==null){
			progress = new ProgressMonitor(chat.getWin(), "文件接收", "", 0, 
					(int)data.getFileLen()/1024);
        	progress.setNote("已完成"+0 + "%");
            progress.setProgress(0);
		}
		long start = data.getPoint();
		RandomAccessFile randomAccessFile = new RandomAccessFile(data.getDistPath(), "rw");
		
        long remain =  data.getFileLen()-start;//剩余的
        
        randomAccessFile.seek(start); //将文件指针定位到start
        
        randomAccessFile.write(data.getMsgContent());//从start字节开始写数据
        randomAccessFile.close();
        
        cnt++;
        
        if(cnt%30==0){
        	float process = ((float)data.getPoint()/(float)data.getFileLen())*100;
            progress.setNote("已完成"+process + "%");
            progress.setProgress((int)data.getPoint()/1024);
        	System.out.println("已完成"+process + "%");
        }
        
        data.setFromIp(toIp);
		data.setToIp(fromIp);
		data.setFlag((byte)2);
		data.setMsgContent("".getBytes(CharsetUtil.UTF_8));
		data.setPoint((cnt-1)*GlobalConst.BYTE_NUM);
		ctx.writeAndFlush(data).sync();
        
		//最后一批，关闭
        if(remain<GlobalConst.BYTE_NUM){
        	progress.close();
        	ctx.close();
        	System.out.println("完成");
        }

        /*if(byteRead!=GlobalConst.BYTE_NUM){
        	Thread.sleep(1000);
        	channelInactive(ctx);
        }*/
       
    }
}
